package cn.iocoder.yudao.module.yyzx.service.outgoing;

import cn.iocoder.yudao.module.yyzx.dal.dataobject.customer.CustomerDO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.yyzx.controller.admin.outgoing.vo.*;
import cn.iocoder.yudao.module.yyzx.dal.dataobject.outgoing.OutgoingDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.yyzx.dal.mysql.outgoing.OutgoingMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.yyzx.enums.ErrorCodeConstants.*;

/**
 * 外出登记 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class OutgoingServiceImpl implements OutgoingService {

    @Resource
    private OutgoingMapper outgoingMapper;
    @Resource
    private cn.iocoder.yudao.module.yyzx.service.outgoing.mysql.customer.CustomerMapper customerMapper;

    @Override
    public Integer createOutgoing(OutgoingSaveReqVO createReqVO) {
        // 插入
        OutgoingDO outgoing = BeanUtils.toBean(createReqVO, OutgoingDO.class);
        outgoingMapper.insert(outgoing);
        // 返回
        return outgoing.getOutingId();


    }

    @Transactional
    @Override
    public void updateOutgoing(OutgoingRespVO updateReqVO) {
        // 校验存在
        validateOutgoingExists(updateReqVO.getOutingId());
        // 更新
        OutgoingDO updateObj = BeanUtils.toBean(updateReqVO, OutgoingDO.class);
        CustomerDO customerDO = BeanUtils.toBean(updateReqVO, CustomerDO.class);
        customerMapper.updateById(customerDO);
        outgoingMapper.updateById(updateObj);
    }

    @Override
    public void deleteOutgoing(Integer id) {
        // 校验存在
        validateOutgoingExists(id);
        // 删除
        outgoingMapper.deleteById(id);
    }

    private void validateOutgoingExists(Integer id) {
        if (outgoingMapper.selectById(id) == null) {
            throw exception(OUTGOING_NOT_EXISTS);
        }
    }

    @Override
    public OutgoingRespVO getOutgoing(Integer id) {
        return outgoingMapper.selectByRecordId(id);
    }

    @Override
    public PageResult<OutgoingPageReqVO> getOutgoingPage(OutgoingPageReqVO pageReqVO) {
        return outgoingMapper.selectPage(pageReqVO);
    }
}